﻿using System;
using System.Reflection;
using CoreEx.DynamicInvoker;

namespace CoreEx.Common.Implementation.Mediator
{    
    public class WeakAction : WeakReference
    {
        private MethodInfo _methodInfo;

        public WeakAction(Delegate actionDelegate) : base(actionDelegate.Target)
        {                        
            _methodInfo = actionDelegate.Method;
        }

        public void Invoke(object argument)
        {           
            //Create a hard reference to the invocation target
            //so that we safely can check for null.
            var invocationTarget = Target;
            
            //The target has been collection by the Garbarge collection.
            if (invocationTarget == null)
                return;

            //Invoke the target method.
            _methodInfo.DynamicInvoke(invocationTarget, argument);            
        }        
    }


    

}
